//
//  memoWidgetViewModel.swift
//  memoWidgetExtension
//
//  Created by DaleGuo on 2023/10/8.
//

import CoreData
import Foundation

class MemoWidgetViewModel: ObservableObject {
    // 不能引入，引入就不能刷新
//    private let memoDateService = MemoDataService.memoDataService
//    private let homeVM = HomeViewModel.share
    var viewContext = PersistenceController.shared.viewContext
    
    public static let share = MemoWidgetViewModel()
    
    func toggle_todo(id: String) {
        let todo = getMemo().todos.first { todo in
            todo.id == id
        }!
        
        todo.is_completed.toggle()
        save()

    }
    
    func getMemo() -> MemoEntity {
        let request = NSFetchRequest<MemoEntity>(entityName: "MemoEntity")
        request.sortDescriptors = [NSSortDescriptor(keyPath: \MemoEntity.updated_date_, ascending: false), NSSortDescriptor(keyPath: \MemoEntity.title_, ascending: true)]
        
//        request.fetchLimit = 1
    
        do {
            var memos = try viewContext.fetch(request)
//                return MemoEntity(title: "Create u memo!", content: "🎉🎉🎉", updated_time: Date())
            
            memos = memos.filter { memo in
                memo.del_flag == false
            }
            
            return memos.first ?? MemoEntity(title: "Create u memo!", content: "🎉🎉🎉", updated_time: Date())
        } catch {
            print("Error fetching portfolio entity: \(error)")
        }
        
        return MemoEntity(title: "Create u memo!", content: "🎉🎉🎉", updated_time: Date())
    }
    
    func save() {
        do {
            try viewContext.save()
        } catch {
            print("Error saving data! \(error)")
        }
    }
}
